//@ sourceURL=/static/modules/mapped/mapped_add.js
let queryTableUrl = '/update/queryTable' //查询表
let queryFileUrl = '/update/queryFile'   //查询字段
let queryWhereUrl = '/update/queryWhere' //查询字典
let addMapperUrl = '/mapper/addMapper'                //增加映射配置
let updateMapperUrl = '/mapper/updateMapper'          //修改映射配置
let updateMapperByIdUrl = '/mapper/updateMapperById'  //详情
//mappedAddView.type
var mappedAddView = new View({
    name: 'mapped_add',
    init_page() {
        if (mappedAddView.type === 'edit') {
            $('#mapped_add_container .page-title').html('编辑');
            mappedAddView.fn.detailInit()
        } else {
            $('#mapped_add_container .page-title').html('新建');
            mappedAddView.fn.getTableData()
        }
    }
});
// 临时存储编辑的目标表名
mappedAddView.tto = '';
mappedAddView.editTableList ={}
// 是否自动匹配过
mappedAddView.autoMatchFalg = false;
// 第二步目标表只加载一次
mappedAddView.SearchTableFalg = false;

// 所有的表
mappedAddView.allTable = []
// 选中的表
mappedAddView.checkedTable = []
// 匹配（第三步）
mappedAddView.mappedCol = {
    targetCol:[],
    allColAry:[],
    allColObj:{},
    subList:[]
}
// 新增过滤条件数据（第四步）
mappedAddView.addTermData = []
mappedAddView.addTermDataBack = []
/**
 * 绑定插件
 */
// 拖拽
mappedAddView.use(new Drag({
    name: 'mapped_drag',
    container_selector: '.drag-container',
    list_selector:'.drag-list'
    // delay: true,
}))
mappedAddView.use(new Form({
    name:'source_table_form',
    selector: '#source_table_form',
    delay: true,
    before_callback(data) {
        mappedAddView.plugins.mapped_drag.updataFieldRelation(data);
        mappedAddView.plugins.source_table_container.close();
        return false;
    }
}))


//初始化主表格
mappedAddView.use(new Table({
    name:'mapped_add_list',
    selector: '#mapped_add_list',
    paging: false,//设置无分页
    data: mappedAddView.mappedCol.subList,
    init_complete() {
        // 监听表的回掉
        $(document).on('changed.bs.select','#mapped_add_list .table-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
            let e = clickedIndex.currentTarget
            mappedAddView.fn.addTermGetTableColData(e,'mapped')
        })
        // 监听字段的回掉
        $(document).on('changed.bs.select','#mapped_add_list .col-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
            let e = clickedIndex.currentTarget
            mappedAddView.fn.addTermTableColChange(e,'mapped')
        })
    }
}))

//过滤条件
mappedAddView.use(new Dialog({
    name: 'add_term_container',
    title: '编辑过滤条件',
    width: '1000px',
    container_selector: '#add_term_container',
    init_callback: function () {
        if(mappedAddView.addTermDataBack.length > 0){
            mappedAddView.addTermData = JSON.parse(JSON.stringify(mappedAddView.addTermDataBack))
        }else {
            mappedAddView.addTermData = [{
                tName:'',
                colNameData: {
                    colName:'',
                    colNameList:[]
                },
                symbol: '',
                text: ''
            }]
        }
        mappedAddView.plugins.add_term_content.options.data = mappedAddView.addTermData;
        //执行表格的初始化
        if(mappedAddView.plugins.add_term_content._table){
            mappedAddView.plugins.add_term_content._table.fnDraw();
        }else {
            mappedAddView.plugins.add_term_content.init();
        }
    }
}))
mappedAddView.use(new Table({
    name: 'add_term_content',
    selector: '#add_term_content',
    paging: false,//设置无分页
    data: mappedAddView.addTermData,
    delay: true,//默认会执行init方法,如果添加次参数就不会执行init方法,需要手动调用
    init_complete() {
        // 监听符号的回掉
        $(document).on('changed.bs.select','#add_term_content .symbol[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
            let e = clickedIndex.currentTarget
            mappedAddView.fn.addTermSymbolChange(e)
        });
        // 监听表的回掉
        $(document).on('changed.bs.select','#add_term_content .table-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
            let e = clickedIndex.currentTarget
            mappedAddView.fn.addTermGetTableColData(e)
        });
        // 监听字段的回掉
        $(document).on('changed.bs.select','#add_term_content .col-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
            let e = clickedIndex.currentTarget
            mappedAddView.fn.addTermTableColChange(e)
        });
    }
}))

//源表关系弹窗
mappedAddView.use(new Dialog({
    name: 'source_table_container',
    title: '添加关系',
    width: '600px',
    container_selector: '#source_table_container',
    init_callback: function () {
        //执行表格的初始化
        mappedAddView.plugins['source_table_content'].init();
        mappedAddView.plugins.source_table_form.init();
    }
}))
mappedAddView.use(new Table({
    name: 'source_table_content',
    selector: '#source_table_content',
    paging: false,//设置无分页
    delay:true,
    data:[],
    init_complete() {
        // this.$table.find('.selectpicker').selectpicker($.po('selectpicker', { container: 'body' }));
    }
}))


/**
 * 方法
 */
mappedAddView.fn = {
    // 获取表
    getTableData()  {
        let data = wdUtil.formToJson($('#drag-list-form'))
        let url = queryTableUrl
        if(data.tName){
            url = queryTableUrl + '?tName='+data.tName
        }
        wdAjax.post({
            url: url,
            cache: false, //禁用缓存
            data: {},
            success: result => {
                $('#drag-list').empty()
                if(!mappedAddView.SearchTableFalg){
                    mappedAddView.allTable = result
                    $('#select-target-table').html('<option value="">请选择</option>')
                }
                result.forEach((item, index) => {
                    // 初始化左侧菜单
                    $('#drag-list').append(`<li data-index="${index}" data-tnandc="${item.tNAndC}" data-tcomments="${item.tComments}" data-talias="${item.tAlias}" data-tname="${item.tName}" data-tid="${item.tId}"> ${item.tAlias}</li>`);
                    if(!mappedAddView.SearchTableFalg){
                        // 初始化目标表选择
                        $('#select-target-table').append(`<option value="${item.tId}">${item.tAlias}</option>`)
                    }
                })
                // 初始下拉框
                $('#select-target-table[data-plugin="selectpicker"]').data().selectpicker.refresh()
                $('#select-target-table').on('changed.bs.select', e => {
                    mappedAddView.fn.targetTableChange(e);
                });
                //
                mappedAddView.SearchTableFalg = true
                if(mappedAddView.type!=='edit')
                    mappedAddView.plugins['mapped_drag'].events();

            }
        })
    },
    // 主表回掉
    targetTableChange(e){
        let value = e.currentTarget.value
        if(!value){
            return
        }
        wdAjax.post({
            url: queryFileUrl,
            cache: false, //禁用缓存
            data: {tid: value, validFlag: 0},
            success: result => {
                mappedAddView.checkedTable = mappedAddView.plugins['mapped_drag'].getData('array')
                // 初始化抽取设置表
                $('#select-table').html(`<option value="">请选择</option><option value="${mappedAddView.checkedTable[0].tid}">${mappedAddView.checkedTable[0].name}</option>`)
                $('#select-table[data-plugin="selectpicker"]').data().selectpicker.refresh()
                $(document).on('changed.bs.select','#select-table',e => {
                    let val = e.currentTarget.value
                    mappedAddView.fn.getTableColData({tid: val, validFlag: 0})
                })
                // 保存目标表字段
                mappedAddView.mappedCol.targetCol = result
                let ary = []
                result.forEach( item =>{
                    let obj ={
                        to:item.colName,
                        table:'',
                        colNameData:{
                            colName:'',
                            colNameList:[]
                        }
                    }
                    ary.push(obj)
                })
                mappedAddView.plugins.mapped_add_list.options.data = ary
                mappedAddView.mappedCol.subList = ary
                mappedAddView.plugins.mapped_add_list._table.fnDraw();
                // 监听表的回掉
                $(document).on('changed.bs.select','#mapped_add_list .table-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
                    let e = clickedIndex.currentTarget
                    mappedAddView.fn.addTermGetTableColData(e,'mapped')
                });
                // 监听字段的回掉
                $(document).on('changed.bs.select','#mapped_add_list .col-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
                    let e = clickedIndex.currentTarget
                    mappedAddView.fn.addTermTableColChange(e,'mapped')
                });
            }
        })
    },
    // 获取表名称
    getTableName(id){
        if(!id) return
        let name = ''
        if(mappedAddView.type === 'edit'){
            for(var i =0;i<mappedAddView.checkedTable.length;i++){
                if(id == mappedAddView.checkedTable[i].tid ){
                    name =  mappedAddView.checkedTable[i].name
                    break
                }
            }
        }else {
            for(var i =0;i< mappedAddView.allTable.length;i++){
                if(id == mappedAddView.allTable[i].tId){
                    name =  mappedAddView.allTable[i].tName
                    break
                }
            }
        }
        return name
    },
    // 获取字段
    getTableColData(data,col) {
        if (!data.tid) {
            $('#select-table-col').html('<option value="">请选择字段</option>')
            $('#select-table-col[data-plugin="selectpicker"]').data().selectpicker.refresh()
            return false
        }
        wdAjax.post({
            url: queryFileUrl,
            cache: false, //禁用缓存
            data: data,
            success: result => {
                // 先清空下拉框
                $('#select-table-col').html('<option value="">请选择字段</option>')
                // 初始化抽取设置表
                result.forEach(item => {
                    if(col){
                        if(col == item.colName){
                            $('#select-table-col').append(`<option value="${item.colName}" selected>${item.colNAndC}</option>`)
                        }else {
                            $('#select-table-col').append(`<option value="${item.colName}">${item.colNAndC}</option>`)
                        }
                    }else {
                        $('#select-table-col').append(`<option value="${item.colName}">${item.colNAndC}</option>`)
                    }

                })
                $('#select-table-col[data-plugin="selectpicker"]').data().selectpicker.refresh()
            }
        })
    },
    // 自动匹配
    autoMatch(e){
        if(mappedAddView.autoMatchFalg){
            return
        }
        mappedAddView.autoMatchFalg = true
        mappedAddView.mappedCol.allColAry = []
        // 获取已配置表源关系所有表的字段
        mappedAddView.mappedCol.allColObj = mappedAddView.plugins.mapped_drag.getSelectedTableField()
        // mappedAddView.mappedCol.allColObj
        for(var key in mappedAddView.mappedCol.allColObj){
            mappedAddView.mappedCol.allColObj[key].forEach(item => {
                item._pId = key
            })
            mappedAddView.mappedCol.allColAry = mappedAddView.mappedCol.allColAry.concat(mappedAddView.mappedCol.allColObj[key])
        }
        let ary = []
        for(var i =0;i<mappedAddView.mappedCol.targetCol.length;i++){
            let targetCol = mappedAddView.mappedCol.targetCol[i]
            let obj ={
                to:targetCol.colName,
                table:'',
                colNameData:{
                    colName:'',
                    colNameList:[]
                }
            }
            let aryColName = [];
            for(var m =0;m<mappedAddView.mappedCol.allColAry.length;m++){
                let allCol = mappedAddView.mappedCol.allColAry[m]
                if(targetCol.colName == allCol.colName){
                    aryColName.push(allCol)
                }
            }
            if(aryColName.length == 1){

                obj.table = aryColName[0]._pId.substring(1,aryColName[0]._pId.length);
                obj.colNameData.colName = aryColName[0].colName;
                obj.colNameData.colNameList =  mappedAddView.mappedCol.allColObj[aryColName[0]._pId];
                ary.push(obj)
            }else {
                ary.push(obj)
            }
        }
        mappedAddView.plugins.mapped_add_list.options.data = ary
        mappedAddView.mappedCol.subList = ary
        mappedAddView.plugins.mapped_add_list._table.fnDraw();
    },
    // 初始化编辑
    detailInit(){
        let id = mappedAddView.itemId;
        wdAjax.get({
            url: updateMapperByIdUrl,
            cache: false, //禁用缓存
            data: {id: id},
            success: result => {
                mappedAddView.plugins.mapped_drag.tempData = result.transformationTemplate.joins;
                mappedAddView.plugins.mapped_drag.tableList = result.transformationTemplate.tablelist;
                mappedAddView.plugins.mapped_drag.editUpdataData();
                // 获取所有的选中的表
                let checkedTable = result.transformationTemplate.tablelist.slice(0,result.transformationTemplate.tablelist.length-1)
                mappedAddView.checkedTable = []
                checkedTable.forEach(item => {
                    mappedAddView.checkedTable.push({
                        tid : item.id,
                        name : item.name,
                        tname : item.name,
                        talias : item.talias,
                    })
                })
                $('#drag-list').empty()
                mappedAddView.checkedTable.forEach((item, index) => {
                    // 初始化左侧菜单
                    $('#drag-list').append(`<li data-index="${index}" data-tname="${item.tname}" data-tid="${item.tid}"> ${item.talias}</li>`);
                })
                // 初始第二步
                let targetTable = result.transformationTemplate.tablelist.pop()
                $('#select-target-table').html(`<option value="${targetTable.id}" selected>${targetTable.name}</option>`)
                $('#select-target-table').data().selectpicker.refresh();
                // 目标表名称
                mappedAddView.tto = result.dmpMapFile.tto
                // 初始第三步
                $('#inputRadiosUnchecked').parent().hide();
                mappedAddView.mappedCol.subList = []
                result.transformationTemplate.mapping.forEach(item => {
                    let objItem = {
                        to:item.to,
                        table:'',
                        colNameData:{
                            colName:item.from,
                            colNameList:[]
                        }
                    }

                    if(item.table){
                        objItem.table = mappedAddView.plugins.mapped_drag.queryTableByName(item.table).id;
                    }
                    if(item.from){
                        objItem.colNameData.colNameList.push({colName:item.from,_pId : objItem.table})
                    }
                    mappedAddView.mappedCol.subList.push(objItem)
                })
                mappedAddView.plugins.mapped_add_list.options.data = mappedAddView.mappedCol.subList
                mappedAddView.plugins.mapped_add_list._table.fnDraw();
                // 监听字段的点击
                $(document).on('loaded.bs.select','#mapped_add_list .col-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
                    mappedAddView.fn.editGetTTableCol(clickedIndex.currentTarget,'mapped')
                });
                // 初始第四步
                let str = ``
                mappedAddView.addTermData = []
                if(result.transformationTemplate.filterConditions.rules){
                    result.transformationTemplate.filterConditions.rules.forEach((item,index) => {
                        let obj = {
                            tName:'',
                            colNameData: {
                                colName:'',
                                colNameList:[]
                            },
                            symbol: '',
                            text: ''
                        }
                        if(item.indexOf('is null') !== -1){
                            let a = item.split('is null')
                            obj.symbol = 'is null'
                            let b = a.split('.')
                            obj.colNameData.colName = b[1]
                            obj.tName = mappedAddView.plugins.mapped_drag.queryTableByName(b[0]).id
                        }else if(item.indexOf('is not null') !== -1){
                            let a = item.split('is not null')
                            obj.symbol = 'is not null'
                            let b = a.split('.')
                            obj.tName = mappedAddView.plugins.mapped_drag.queryTableByName(b[0]).id
                            obj.colNameData.colName = b[1]
                        }else {
                            let ary = item.match(/(.*?)\s(.*?)\s(.*)/)
                            let a = ary[1].split('.')
                            obj.tName = mappedAddView.plugins.mapped_drag.queryTableByName(a[0]).id
                            obj.colNameData.colName = a[1]
                            obj.symbol = ary[2]
                            obj.text = ary[3]
                        }
                        obj.colNameData.colNameList.push({colName:obj.colNameData.colName,_pId:obj.tName})
                        mappedAddView.addTermData.push(obj)
                        if(index === 0){
                            str += `<span>where ${item}</span>`
                        }else {
                            str += `<span>and where ${item}</span>`
                        }
                    })
                    mappedAddView.addTermDataBack = JSON.parse(JSON.stringify(mappedAddView.addTermData))
                    $('#add-term-btn').html('编辑')
                }else {
                    mappedAddView.addTermData = [{
                        tName:'',
                        colNameData: {
                            colName:'',
                            colNameList:[]
                        },
                        symbol: '',
                        text: ''
                    }]
                }

                mappedAddView.plugins.add_term_content.options.data = mappedAddView.addTermData
                if (mappedAddView.plugins.add_term_content._table) {
                    mappedAddView.plugins.add_term_content._table.fnDraw();
                } else { 
                    mappedAddView.plugins.add_term_content.init();
                }
                // 监听字段的点击
                $(document).on('loaded.bs.select','#add_term_content .col-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
                    mappedAddView.fn.editGetTTableCol(clickedIndex.currentTarget)
                });
                $('#add-term-list p').html(str)
                // 初始第五步 初始化抽取设置表
                let col = result.transformationTemplate.controls[result.transformationTemplate.controls.length-1].value
                if(col){
                    $('#select-table').html(`<option value="">请选择</option><option value="${mappedAddView.checkedTable[0].tid}" selected>${mappedAddView.checkedTable[0].name}</option>`)
                    mappedAddView.fn.getTableColData({tid: mappedAddView.checkedTable[0].tid, validFlag: 0},col)
                }else {
                    $('#select-table').html(`<option value="">请选择</option><option value="${mappedAddView.checkedTable[0].tid}">${mappedAddView.checkedTable[0].name}</option>`)
                }
                $('#select-table[data-plugin="selectpicker"]').data().selectpicker.refresh()
                $('#select-table').on('changed.bs.select', e => {
                    let val = e.currentTarget.value
                    mappedAddView.fn.getTableColData({tid: val, validFlag: 0})
                });
            }
        })
    },
    // 编辑字段回掉
    editGetTTableCol(e,type){
        let dom = $(e)
        let index = dom.parents('tr').index()
        let tableId = dom.data().id
        let row = mappedAddView.addTermData[index]
        if(type === 'mapped'){
            row = mappedAddView.mappedCol.subList[index]
        }
        if(row.colNameData.colNameList.length === 1 && !row.colNameData.colNameList[0].colNAndC){
            if(mappedAddView.editTableList[tableId]){
                let colList = mappedAddView.editTableList[tableId]
                // 初始化字段下拉框
                dom.html('<option value="">请选择字段</option>')
                colList.forEach(item => {
                    if(row.colNameData.colName == item.colName){
                        dom.append(`<option value="${item.colName}" selected>${item.colName}</option>`)
                    }else {
                        dom.append(`<option value="${item.colName}">${item.colName}</option>`)
                    }
                })
                dom.data().selectpicker.refresh()
            }else {
                wdAjax.post({
                    url: queryFileUrl,
                    cache: false, //禁用缓存
                    data: {tid: tableId, validFlag: 0},
                    success: result => {
                        mappedAddView.mappedCol.subList[index].colNameData.colNameList = result;
                        mappedAddView.editTableList[tableId] = result
                        // 初始化字段下拉框
                        dom.html('<option value="">请选择字段</option>')
                        result.forEach(item => {
                            if(row.colNameData.colName == item.colName){
                                dom.append(`<option value="${item.colName}" selected>${item.colName}</option>`)
                            }else {
                                dom.append(`<option value="${item.colName}">${item.colName}</option>`)
                            }
                        })
                        dom.data().selectpicker.refresh()
                    }
                })
            }

        }
    },


    // 过滤条件--------------------------------------
    // 新增条件
    addTerm() {
        mappedAddView.plugins.add_term_container.show();
    },
    // 新增一项条件
    addTermAdd(e) {
        let index = $(e).parents('tr').index();
        let row = mappedAddView.plugins.add_term_content._table.fnGetData(index)
        let flag= mappedAddView.fn.isSubmit()
        if (flag) {
            alertify.error('请填写完整数据，再新增');
            return false
        }
        mappedAddView.addTermData.push({
            tName:'',
            colNameData: {
                colName:'',
                colNameList:[]
            },
            symbol: '',
            text: ''
        })
        mappedAddView.plugins.add_term_content._table.fnDraw();
        // 监听字段的回掉
        $(document).on('changed.bs.select','#add_term_content .col-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
            let e = clickedIndex.currentTarget
            mappedAddView.fn.addTermTableColChange(e)
        });
    },
    // 删除一项条件
    addTermDel(e) {
        if(mappedAddView.addTermData.length === 1){
            alertify.error('必须有一条数据!');
            return false
        }
        let index = $(e).parents('tr').index();
        mappedAddView.addTermData.splice(index, 1);
        mappedAddView.plugins.add_term_content._table.fnDraw();
    },
    // 获取字段
    addTermGetTableColData(e,type) {
        let val = $(e).val();
        let index = $(e).parents('tr').index();
        if(type && type == 'mapped'){
            mappedAddView.mappedCol.subList[index].table = val;
        }else {
            mappedAddView.addTermData[index].tName = val;
        }

        let dom = $(e).parents('tr').find('td:eq(2)').find('.col-name[data-plugin="selectpicker"]')
        // 先清空下拉框
        dom.html('<option value="">请选择字段</option>')
        dom.data().selectpicker.refresh()
        if (!val) {
            return false
        }
        wdAjax.post({
            url: queryFileUrl,
            cache: false, //禁用缓存
            data: {tid: val, validFlag: 0},
            success: result => {
                // 保存字段
                if(type && type == 'mapped'){
                    mappedAddView.mappedCol.subList[index].colNameData.colNameList = result;
                }else {
                    mappedAddView.addTermData[index].colNameData.colNameList = result;
                }
                // 初始化字段下拉框
                result.forEach(item => {
                    dom.append(`<option value="${item.colName}">${item.colNAndC}</option>`)
                })
                dom.data().selectpicker.refresh()
                // 监听字段的回掉
                $(document).on('changed.bs.select','#add_term_container .col-name[data-plugin="selectpicker"]', (clickedIndex,newValue,oldValue) => {
                    let e = clickedIndex.currentTarget
                    mappedAddView.fn.addTermTableColChange(e)
                });
            }
        })
    },
    // 选择字段
    addTermTableColChange(e,type){
        let val = $(e).val();
        let index = $(e).parents('tr').index();
        if(type && type == 'mapped'){
            mappedAddView.mappedCol.subList[index].colNameData.colName = val;
        }else {
            mappedAddView.addTermData[index].colNameData.colName = val;
        }
    },
    // 符号选中
    addTermSymbolChange(e){
        let val = $(e).val();
        let index = $(e).parents('tr').index();
        if(val === 'is not null' || val === 'is null'){
            $(e).parents('tr').find('.symbol-input').val('').prop('disabled', true)
            mappedAddView.addTermData[index].text = '';
        }else {
            $(e).parents('tr').find('.symbol-input').prop('disabled', false)
        }
        mappedAddView.addTermData[index].symbol = val;
    },
    // 参数填写
    inputBlur(e){
        let val = $(e).val().trim();
        let index = $(e).parents('tr').index();
        $(e).val(val)
        mappedAddView.addTermData[index].text = val
    },
    // 是否有空白
    isSubmit(){
        let flag = false
        for (var i = 0; i < mappedAddView.addTermData.length; i++) {
            let row = mappedAddView.addTermData[i]
            if(!row.tName || !row.colNameData.colName || !row.symbol){
                flag = true
            }
            if(row.symbol && row.symbol !== 'is null' && row.symbol !== 'is not null' && !row.text){
                flag = true
            }
        }
        return flag
    },
    // 提交
    addTermSubmit(){
        let flag= mappedAddView.fn.isSubmit()
        if (flag) {
            alertify.error('请填写完整数据，再提交');
            return false
        }
        $('#add-term-btn').html('编辑')
        mappedAddView.addTermDataBack = JSON.parse(JSON.stringify(mappedAddView.addTermData))
        let str = ``
        mappedAddView.addTermDataBack.forEach((item,index) => {
            let name = mappedAddView.fn.getTableName(item.tName)
            if(index === 0){
                str += `<span>where ${name}.${item.colNameData.colName} ${item.symbol} ${item.text}</span>`
            }else {
                str += `<span>and where ${name}.${item.colNameData.colName} ${item.symbol} ${item.text}</span>`
            }
        })
        $('#add-term-list p').html(str)
        mappedAddView.plugins.add_term_container.close();
    },
    // 过滤条件end--------------------------------------


    // 最终提交
    mappedAddSub(){
        if(mappedAddView.checkedTable.length === 0){
            alertify.error('第一步信息不完整');
            return
        }
        if(!$('#select-target-table').val()){
            alertify.error('第二步未选择');
            return
        }
       let data = {
           addMapperPo: {colName: "",tfroms: "",tid: "",tto: "",tfromsIds:"",tfromsAlias:""},
           transformationTemplatePo: {
               filterConditions: {
                   rules: []
               },
               joins: [],
               mapping: []
           }
       }
        mappedAddView.checkedTable.forEach((item,index) => {
            if(index == mappedAddView.checkedTable.length-1){
                data.addMapperPo.tfroms+=item.name
                data.addMapperPo.tfromsIds+=item.tid
                data.addMapperPo.tfromsAlias+=item.talias
            }else {
                data.addMapperPo.tfroms+=item.name + '|'
                data.addMapperPo.tfromsIds+=item.tid + '|'
                data.addMapperPo.tfromsAlias+=item.talias + '|'
            }
        })
       // 第一步
        data.transformationTemplatePo.joins = mappedAddView.plugins['mapped_drag'].dataToParams()
        // 第二步
        data.addMapperPo.tid = $('#select-target-table').val();
        if(mappedAddView.type === 'edit'){
            data.addMapperPo.tto = mappedAddView.tto
        }else {
            data.addMapperPo.tto = mappedAddView.fn.getTableName(data.addMapperPo.tid);
        }
        // 第三步
        let mappedColFalg =false
        for(var i =0;i<mappedAddView.mappedCol.subList.length;i++){
            let item = mappedAddView.mappedCol.subList[i]
            if(item.table && !item.colNameData.colName){
                mappedColFalg = true
                break
            }
            let obj = {
                from: item.colNameData.colName,
                table: mappedAddView.fn.getTableName(item.table),
                to: item.to
            }
            data.transformationTemplatePo.mapping.push(obj)
        }
        if(mappedColFalg){
            alertify.error('第三步选择了表，必须选字段');
            return
        }
        // 第四步
        mappedAddView.addTermDataBack.forEach(item => {
            let name = mappedAddView.fn.getTableName(item.tName)
            let str = `${name}.${item.colNameData.colName} ${item.symbol} ${item.text}`
            data.transformationTemplatePo.filterConditions.rules.push(str)
        })

       // 第五步
        if($('#select-table').val() &&  !$('#select-table-col').val()){
            alertify.error('第五步选择了抽取表，必须选择抽取字段');
            return
        }
        data.addMapperPo.colName = $('#select-table-col').val();
        let url = addMapperUrl
        if(mappedAddView.type === 'edit'){
            data.id = mappedAddView.itemId
            url = updateMapperUrl
        }
        wdAjax.post({
            url: url,
            cache: false, //禁用缓存
            data: data,
            success: result => {
                alertify.success('操作成功')
                router.to('mapped')
            }
        })
    },
    // 初始化dom
    render: {
        select(data, type) {
            return `<select class="form-control selectpicker" name="" data-plugin="selectpicker">
                <option value="">请选择</option>
                <option value="">1</option>
                <option value="">2</option>
            </select>`
        },
        // 新增过滤条件 关系栏
        relation(data, type, row) {
            if (row.index !== 1) {
                return `<select class="form-control selectpicker" data-plugin="selectpicker">
                <option value="">and</option>
            </select>`
            }
        },
        // 表选择dom
        addTermTableSelect(data, type, row){
            let checkedTable = mappedAddView.checkedTable;
            if(!checkedTable){
                return false
            }
            let strHtml = ``
            checkedTable.forEach( item => {
                let strItem = `<option value="${item.tid}">${item.talias}</option>`
                if(data == item.tid){
                    strItem = `<option value="${item.tid}" selected>${item.talias}</option>`
                }
                strHtml += strItem
            })
            return `<select class="form-control table-name selectpicker" data-plugin="selectpicker">
                <option value="">请选择</option>
                ${strHtml}
            </select>`
        },
        // 字段选择dom
        addTermColSelect(data, type, row){
            let strHtml = ``
            if(data.colNameList && data.colNameList.length){
                data.colNameList.forEach(item => {
                    if(mappedAddView.type === 'edit'){
                        let strItem = `<option value="${item.colName}">${item.colName}</option>`
                        if(data.colName == item.colName){
                            strItem = `<option value="${item.colName}" selected>${item.colName}</option>`
                        }
                        strHtml += strItem
                    }else {
                        let strItem = `<option value="${item.colName}">${item.colNAndC}</option>`
                        if(data.colName == item.colName){
                            strItem = `<option value="${item.colName}" selected>${item.colNAndC}</option>`
                        }
                        strHtml += strItem
                    }

                })
            }
            if(mappedAddView.type === 'edit' && data.colNameList.length){
                return `<select class="form-control col-name selectpicker" data-plugin="selectpicker" data-id="${data.colNameList[0]._pId}">
                <option value="">请选择字段</option>
                ${strHtml}
            </select>`
            }else {
                return `<select class="form-control col-name selectpicker" data-plugin="selectpicker">
                <option value="">请选择字段</option>
                ${strHtml}
            </select>`
            }
        },
        //Symbol
        symbol(data, type, row){
            let symbolList = ['>','<','=','>=','<=','!=','is not null','is null']
            let strHtml =``
            symbolList.forEach(item => {
                let strItem = `<option value="${item}">${item}</option>`
                if(data == item){
                    strItem = `<option value="${item}" selected>${item}</option>`
                }
                strHtml += strItem
            })
            return `<select class="form-control symbol selectpicker" data-plugin="selectpicker">
                <option value="">请选择</option>
                ${strHtml}
            </select>`
        },
        // 初始输入框
        initInput(data, type){
            return `<input class="width-p-100 form-control symbol-input" type="text" value="${data}" onBlur="mappedAddView.fn.inputBlur(this)"/>`
        },
        // 新增条件初始操作栏
        operation(data, type, row) {
            var html = '<button class="btn btn-primary margin-right-10 grid-delete-btn" data-name="' + data.name + '" data-id="' + data.userId + '" type="button" onClick="mappedAddView.fn.addTermAdd(this)" >添加</button>' +
                '<button class="btn btn-primary margin-right-10 grid-delete-btn" data-name="' + data.name + '" data-id="' + data.userId + '" type="button" onClick="mappedAddView.fn.addTermDel(this)" >删除</button>'
            return html;
        },
        relationMname(data, type, row) {
            if (data instanceof Array) {
                let selectArr = [];
                data.map(item => {
                    selectArr.push({
                        key: item.colNAndC,
                        value:item.colId,
                        selected:item.selected||false
                    })
                })
                return wdUtil.selectTohtml({name:'left-field',list:selectArr});
            } else {
                return `${data.colNAndC}<input type="text" value="${data.colId}" class="hide" name="left-field"/>`
            }
        },
        relationTto(data, type, row) {
            if (data instanceof Array) {
                let selectArr = [];
                data.map(item => {
                    selectArr.push({
                        key: item.colNAndC,
                        value: item.colId,
                        selected:item.selected||false
                    })
                })
                return wdUtil.selectTohtml({name:'right-field',list:selectArr});
            } else {
                return `${data.colNAndC}<input type="text" value="${data.colId}" class="hide" name="right-field"/>`
            }

        },
    }

}
/**
 * 事件
 */
mappedAddView._event = () => {

}
